package base.filter.lib;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
 * 产生验证
 *
 */
@SuppressWarnings("all")
public class ValiImgAction extends ActionSupport implements java.io.Serializable{
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) {
		response.setContentType("image/jpeg");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		HttpSession session = request.getSession();
		// 创建图象
		int width = 60, height = 20;
		BufferedImage bimg = new BufferedImage(width, height,
				BufferedImage.TYPE_3BYTE_BGR);
		Graphics g = bimg.getGraphics();// 取得图形上下文

		g.setColor(getRandColor(200, 250));// 设置背景颜色
		g.fillRect(0, 0, width, height);
		g.setFont(new Font("Times New Roman", Font.PLAIN, 18));// 设置字体

		g.setColor(getRandColor(160, 200));// 随机产生155条随机线
		Random rd = new Random();
		for (int i = 0; i < 155; i++) {
			int x = rd.nextInt(width);
			int y = rd.nextInt(height);
			int x1 = rd.nextInt(12);
			int y1 = rd.nextInt(12);
			g.drawLine(x, y, x + x1, y + y1);
		}

		// 取4位随机数
		String sRand = "";
		for (int j = 0; j < 4; j++) {
			String rand = String.valueOf(rd.nextInt(10));
			sRand += rand;
			// 把随机数写入图象
			// 种子相近 颜色相同 因此直接生成
			g.setColor(new Color(20 + rd.nextInt(110), 20 + rd.nextInt(110),
					20 + rd.nextInt(110)));
			g.drawString(rand, 13 * j + 6, 16);
		}
		session.setAttribute("rand", sRand);
		g.dispose();
		ServletOutputStream responseotOutputStream;
		try {
			responseotOutputStream = response.getOutputStream();
			ImageIO.write(bimg, "JPEG", responseotOutputStream);// 输出到页面
			responseotOutputStream.flush();
			responseotOutputStream.close();
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	}

	Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

     public String execute() throws Exception {
		HttpServletRequest  request=ServletActionContext.getRequest();
		HttpServletResponse response=ServletActionContext.getResponse();
		processRequest(request, response);
		return null;
	}

	
}
